package com.wang.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.wang.study.Proxy.JdkDynamicProxyUtil;
import com.wang.study.commons.BaseServlet;
import com.wang.study.commons.CommonsUtils;
import com.wang.study.model.Order;
import com.wang.study.model.User;
import com.wang.study.service.OrderService;
import com.wang.study.service.impl.OrderServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/order.do")
public class OrderController extends BaseServlet {
    private OrderService orderService =  new JdkDynamicProxyUtil<OrderService>().getProxyObject(new OrderServiceImpl());

    /**
     * 支付操作
     * @param request
     * @param resp
     * @throws IOException
     */
    public void creatOrder(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        //获取uid
        String uid = request.getParameter("uid");
        String total = request.getParameter("total");
        System.out.println(total);
        //获取购物车的ids
        String[] gids = request.getParameterValues("gid");
        System.out.println(gids);
        ArrayList<Integer> ids = new ArrayList<>();
        for (String gid : gids) {
            ids.add(Integer.valueOf(gid));
        }
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        //生成订单
        Order order = new Order();
        order.setId(CommonsUtils.getRandomString(32));
        order.setMoney(Double.valueOf(total));
        order.setOrdername(loginUser.getAccount()+"0的订单");
        order.setUserid(Integer.valueOf(uid));
        order.setOrdertime(System.currentTimeMillis());
        //获取业务层对象，将订单持久化到数据库中
        orderService.insertOrder(ids,order);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getId();
        //付款金额，必填
        String total_amount = order.getMoney()+"";
        //订单名称，必填
        String subject = order.getOrdername()+"的订单";
        //商品描述，可空
        String body = "智能电器";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        resp.getWriter().println(result);
    }

    /**
     * 展示数据
     * @param request
     * @param resp
     */
    public void showOrderByUserId(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        String uid = request.getParameter("uid");
        List<Order> orders = orderService.showOrderByUserId(uid);
        resp.getWriter().write(new JSONObject().toJSONString(orders));
    }
}
